layui.use(['table','form', 'element'], function () {
    let table = layui.table,
        form = layui.form,
        $ = layui.jquery,
     dropdown = layui.dropdown,
       element = layui.element;

    //方法级渲染
    table.render({
        elem: '#dockerDeploy'
        , url: '/admDockerDeploy/page'
        , toolbar: '#toolbarTable'
        , title: 'docker部署'
        , totalRow: true
        ,skin: 'line'
        , id: "dockerDeploy"
        , cols: [[
            {checkbox: true, fixed: true}
            , {field: 'projectName', title: '项目名称', width: 180, sort: true}
            , {field: 'moduleName', title: '模块名称', width: 200, sort: true}
            , {field: 'namespaceName', title: '命名空间', width: 150, sort: true}
            , {field: 'ip', title: '宿主机ip', width: 130, sort: true}
            , {field: 'containerStatusName', title: '容器状态', width: 100, sort: true,templet: function (d) {
                    let className = '';
                    if (d.containerStatusName == 'running'){
                        className = 'layui-bg-green'
                    }
                    if (d.containerStatusName == 'exited') {
                        className = 'layui-bg-red'
                    }
                    if (d.containerStatusName == 'paused') {
                        className = 'layui-bg-warm'
                    }
                    if (d.containerStatusName == '连接失败') {
                        className = 'layui-bg-gray'
                    }
                    return '<span class = "layui-badge '+className+'" >'+d.containerStatusName+'</span>';
                }}

            , {field: 'enable', title: '是否自动', width: 100, sort: true,templet: '#switchStatus', unresize: true}
            , {field: 'deployStatus', title: '部署状态', width: 300, sort: true,templet: function (d) {
                    //状态：0空闲 1编译中 2代码上传 3镜像构建中 4.构建完毕 5.push仓库 6.拉取镜像 7.开始启动新容器 8.启动成功  9.maven编译失败 10.docker部署失败
                    let ys = '';
                    let statusName = '';
                    let className = '';
                    if (d.deployStatus == 0) {
                        ys='layui-btn-primary'
                        className = 'layui-bg-gray'
                    }else if(d.deployStatus == 10 ||d.deployStatus == 11){
                        ys='layui-btn-danger'
                        className = 'layui-bg-warm'
                    }else {
                        ys='layui-btn-normal'
                        className = 'layui-bg-blue'
                    }
                    statusName = '<span class="layui-badge  '+className+'" style="float:left;">'+d.deployStatusName+'</span>';

                    //***重点***：拼接进度条
                    return '<div style="display:inline"><div style="float:left;width: 150px" class="layui-progress layui-progress-big" lay-showpercent="true">' +
                        '<div class="layui-progress-bar '+ys+'" lay-percent="'+d.progressBar+'%">' +
                        '</div>' +
                        '</div>'+statusName+'' +
                        '</div>'

                }}
            , {field: 'lastDeployDate', title: '更新时间', width: 160, sort: true}
            , {field: 'tag', title: 'tag', width: 80, sort: true}
            , {fixed: 'right', title: '操作', toolbar: '#barDemo', width: 200}
        ]]
        , even: true
        , page: true //是否显示分页
        , skip: true //开启跳页
        , limits: [12,15, 30, 60]
        , width: 1700
        // , height: 'full-150'
        , limit: 12 //每页默认显示的数量
        , parseData: function (res) { //res 即为原始返回的数据
            var data = res.data;
            return {
                "code": status, //解析接口状态   （好像必须是0 才可以）
                "msg": data.desc, //解析提示文本
                "count": data.total, //解析数据长度
                "data": data.records //解析数据列表
            };
        }
        ,done:function (res,currentCount) {
            //***重点***：table渲染完成后渲染element进度条
            element.render()
        }

    });

//监听性别操作
    form.on('switch(statusFilter)', function(obj){
        // layer.tips(this.value + ' ' + this.name + '：'+ obj.elem.checked, obj.othis);
        const params = {
            id: this.value,
            enable: obj.elem.checked ? 0 : 1
        };
        $.ajax({
            url: '/admDockerDeploy/changeStatus',
            data: JSON.stringify(params),
            dataType: "json",
            contentType: "application/json;charset=utf-8",
            type: "PUT",
            success: function (result) {
                layer.msg(result.desc, {icon: 1, time: 3000}, function () {

                })
            }
        })
    });
    //头工具栏事件
    table.on('toolbar(dockerDeploy)', function (obj) {
        let data = table.checkStatus(obj.config.id).data;
        let ids;switch (obj.event) {
            case 'add':
                add();
                break;
            case 'del':
                ids = check(data);
                if (!ids){
                    return
                }
                del(ids);
                break;
            case "startService":
                ids = check(data);
                if (!ids){
                    return
                }
                startService(ids);
                break;
            case "updateTag":
                ids = check(data);
                if (!ids){
                    return
                }
                updateTag(ids);
                break;
            case "restartService":
                ids = check(data);
                if (!ids){
                    return
                }
                restartService(ids);
                break;
            case "stopService":
                ids = check(data);
                if (!ids){
                    return
                }
                stopService(ids);
                break;
            case "pauseService":
                ids = check(data);
                if (!ids){
                    return
                }
                pauseService(ids);
                break;
            case "allLog":
                allLog();
                break;
        }
        ;
    });
    function startService(ids) {
        layer.open({
            type: 2,
            title: '构建部署',
            area: ['550px', '300px'],
            fix: false, //
            closeBtn: false,
            shift: 2,
            shadeClose: true,
            content: ["deploy.html", 'no'],
            success: function (layero, index) {
                const body = layer.getChildFrame('body', index);//获取弹出层的dom元素
                const iframeWin = layero.find('iframe')[0].contentWindow;
                body.find("#ids").val(ids);
            },
            yes: function () {
            }
        });

    }
    function restartService(ids) {
        layer.msg("开始重启", {icon: 1, time: 1000}, function () {
        })
        $.ajax({
            url: '/admDockerDeploy/restartService',
            data:{ids:ids},
            dataType: "json",
            type: "POST",
            success: function (result) {
                layer.msg(result.data, {icon: 1, time: 3000}, function () {
                    search();
                })
            }
        })
    }
    function stopService(ids) {
        layer.msg("停止服务", {icon: 1, time: 1000}, function () {
        })
        $.ajax({
            url: '/admDockerDeploy/stopService',
            data:{ids:ids},
            dataType: "json",
            type: "POST",
            success: function (result) {
                layer.msg(result.data, {icon: 1, time: 2000}, function () {
                    search();
                })
            }
        })
    }
    function pauseService(ids) {
        layer.msg("暂停服务", {icon: 1, time: 1000}, function () {
        })
        $.ajax({
            url: '/admDockerDeploy/pauseService',
            data:{ids:ids},
            dataType: "json",
            type: "POST",
            success: function (result) {
                layer.msg(result.data, {icon: 1, time: 2000}, function () {
                    search();
                })
            }
        })
    }
    function check(data) {
        if (data.length==0){
            layer.msg("请先勾选数据",{icon:2,time:3000});
            return;
        }
        let ids = "";
        for (let i = 0; i < data.length; i++) {
            ids+=data[i].id+","
        }
        ids = ids.substr(0,ids.length-1);
        return ids;
    }
    //监听行工具事件
    table.on('tool(dockerDeploy)', function (obj) {
        const data = obj.data;
        if (obj.event === 'ssh'){
            ssh(data)
        }else if (obj.event === 'docker'){
            docker(data)
        }else if (obj.event === 'more'){
            // 下拉菜单
            dropdown.render({
                elem: this, // 触发事件的 DOM 对象
                show: true, // 外部事件触发即显示
                align: "right", // 右对齐弹出
                data: [
                    {
                        title: "部署日志",
                        id: "log"
                    },
                    {
                        title: "实时日志",
                        id: "instanceLog"
                    },
                    {
                        title: "修改",
                        id: "update"
                    },
                    {
                        title: "删除",
                        id: "del"
                    },
                    {
                        title: "历史",
                        id: "tag"
                    },
                ],
                click: function (menudata) {
                    if (menudata.id === "update") {
                        update(data);
                    } else if (menudata.id === "del") {
                        del(data.id)
                    } else if (menudata.id === "log") {
                        log(data)
                    } else if (menudata.id === "instanceLog") {
                        instanceLog(data)
                    } else if (menudata.id === "tag") {
                        tag(data)
                    }
                }
            });
        }
    });

    function ssh(data) {
        $.ajax({
            type: "get",//方法类型
            dataType: "json",//预期服务器返回的数据类型
            url: "/server/getServerByIp?ip="+data.ip,//url
            success: function (result) {
                if (result.code == 0) {
                    let params = {
                        "ip": data.ip,
                        "username": result.data.username,
                        "password": result.data.password,
                        "port": result.data.port
                    };
                    window["sshParams"] = params;
                    const newWindow = window.open("../ssh/webssh.html");
                    const loop = setInterval(function () {
                        if (newWindow.closed) {
                            clearInterval(loop);
                        } else {
                            newWindow.document.title = data.ip;
                        }
                    }, 1000);
                };
            },
            error: function () {
                alert("异常！");
            }
        });
    }
    function docker(data) {
        $.ajax({
            type: "get",//方法类型
            dataType: "json",//预期服务器返回的数据类型
            url: "/admDocker/getById/"+data.dockerId,//url
            success: function (result) {
                if (result.code == 0) {
                    window.open(result.data.portainerUrl);
                };
            },
            error: function () {
                alert("异常！");
            }
        });
    }
    function instanceLog(data) {
        $.ajax({
            type: "get",//方法类型
            dataType: "json",//预期服务器返回的数据类型
            url: "/admDocker/getById/"+data.dockerId,//url
            success: function (result) {
                if (result.code == 0) {
                    const url = result.data.portainerUrl + "/#!/1/docker/containers/"+data.containerId+"/logs";
                    window.open(url);
                };
            },
            error: function () {
                alert("异常！");
            }
        });
    }
    function tag(data) {
        layer.open({
            type: 2,
            title: '版本记录',
            area: ['1000px', '650px'],
            fix: false, //
            closeBtn: false,
            shift: 2,
            shadeClose: true,
            content: ["tag.html"],
            success: function (layero, index) {
                const body = layer.getChildFrame('body', index);//获取弹出层的dom元素
                const iframeWin = layero.find('iframe')[0].contentWindow;
                body.find("#id").val(data.id);
                body.find("#projectId").val(data.projectId);
                body.find("#namespaceId").val(data.namespaceId);
                body.find("#moduleName").val(data.moduleName);
                if (data.tag==null || data.tag =="") {
                    body.find("#name").html(data.projectName+"/"+data.moduleName+" 暂无版本记录");
                }else {
                    body.find("#name").html(data.projectName+"/"+data.moduleName+" 当前版本:"+data.tag);
                }
                iframeWin.layui.form.render();
            },
            yes: function () {
            }
        });
    }
    function log(data){
        layer.open({
            type: 2,
            title: '部署详情',
            area: ['1000px', '650px'],
            fix: false, //
            closeBtn: false,
            shift: 2,
            shadeClose: true,
            content: ["log.html"],
            success: function (layero, index) {
                const body = layer.getChildFrame('body', index);//获取弹出层的dom元素
                const iframeWin = layero.find('iframe')[0].contentWindow;
                body.find("#id").val(data.id);
                body.find("#projectName").html(data.projectName+"/"+data.moduleName);
                body.find("#ip").html(data.ip);
                iframeWin.layui.form.render();
            },
            yes: function () {
            }
        });
    }
    function del(ids) {
        layer.confirm("确认要移除容器吗，移除容器后不能恢复", { title: "移除确认" }, function (index) {
            $.ajax({
                type: "delete",//方法类型
                dataType: "json",//预期服务器返回的数据类型
                url: "/admDockerDeploy/"+ids,//url
                success: function (result) {
                    if (result.code == 0) {
                        layer.msg(result.data,{icon:1,time:1000},function () {
                            location.reload();
                        });
                    };
                },
                error: function () {
                    alert("异常！");
                }
            });
        })
    }
    function updateTag(ids) {
        layer.open({
            type: 2,
            title: '变更版本号',
            area: ['550px', '300px'],
            fix: false, //
            closeBtn: false,
            shift: 2,
            shadeClose: true,
            content: ["updateTag.html", 'no'],
            success: function (layero, index) {
                const body = layer.getChildFrame('body', index);//获取弹出层的dom元素
                const iframeWin = layero.find('iframe')[0].contentWindow;
                body.find("#ids").val(ids);
            },
            yes: function () {
            }
        });
    }

    function add() {
        layer.open({
            type: 2,
            title: '新增docker节点',
            area: ['900px', '600px'],
            fix: false, //
            closeBtn: false,
            shift: 2,
            shadeClose: false,
            content: ["add.html", 'no'],
            success: function (layero, index) {
                form.render();
            },
            yes: function () {
            }
        });
    }
    let dropData
    function update(data) {
        layer.open({
            type: 2,
            title: '修改docker节点',
            area: ['900px', '600px'],
            fix: false, //
            closeBtn: false,
            shift: 2,
            shadeClose: false,
            content: ["update.html", 'no'],
            success: function (layero, index) {
                const body = layer.getChildFrame('body', index);//获取弹出层的dom元素
                const iframeWin = layero.find('iframe')[0].contentWindow;
                body.find("#id").val(data.id);
                body.find("#projectId").val(data.projectId);
                body.find("#projectName").val(data.projectName);
                body.find("#dockerName").val(data.dockerName);
                body.find("#dockerId").val(data.dockerId);
                body.find("#registryId").val(data.registryId);
                body.find("#registryName").val(data.registryName);
                body.find("#namespaceId").val(data.namespaceId);
                body.find("#namespaceName").val(data.namespaceName);
                body.find("#nacosId").val(data.nacosId);
                body.find("#nacosName").val(data.nacosName);
                body.find("#moduleName").val(data.moduleName);
                body.find("#springProfilesActive").val(data.springProfilesActive);
                body.find("#tag").val(data.tag);
                body.find("#localFile").val(data.localFile);
                body.find("#remoteTargetDirectory").val(data.remoteTargetDirectory);
                body.find("#mountThePath").val(data.mountThePath);
                body.find("#jdkVersion").val(data.jdkVersion);
                body.find("#portBinding").val(data.portBinding);
                body.find("#containerName").val(data.containerName);
// 回显环境配置
                const envConfigs = body.find('.env-configs');
                envConfigs.empty(); // 清空现有的环境配置项
                // 将 JSON 字符串转换为数组
                if (data.envs && data.envs.length > 0) {
                    let envsArray = JSON.parse(data.envs);
                    let isFirst = true; // 添加一个标志，用于控制是否是第一个条目

                    envsArray.forEach(env => {
                        const $newRow = $(
                            '<div class="env-config d-flex align-items-center">' +
                            '   <input type="text" name="envKey[]" placeholder="Key" class="layui-input" style="width: 200px;" value="' + env.key + '">' +
                            '   <span class="equals-sign mx-2">=</span>' +
                            '   <input type="text" name="envValue[]" placeholder="Value" class="layui-input" style="width: 200px;" value="' + env.value + '">' +
                            '   <button type="button" class="layui-btn layui-btn-primary add-env"><i class="layui-icon">&#xe654;</i></button>' +
                            '   <button type="button" class="layui-btn layui-btn-danger remove-env" ' + (isFirst ? 'style="display: none;"' : '') + '><i class="layui-icon">&#xe640;</i></button>' +
                            '</div>'
                        );

                        // 更新标志
                        isFirst = false;

                        envConfigs.append($newRow);
                    });
                } else {
                    // 如果没有环境配置项，则保留一个空的模板
                    const $emptyRow = $(
                        '<div class="env-config d-flex align-items-center">' +
                        '   <input type="text" name="envKey[]" placeholder="Key" class="layui-input" style="width: 200px;">' +
                        '   <span class="equals-sign mx-2">=</span>' +
                        '   <input type="text" name="envValue[]" placeholder="Value" class="layui-input" style="width: 200px;">' +
                        '   <button type="button" class="layui-btn layui-btn-primary add-env"><i class="layui-icon">&#xe654;</i></button>' +
                        '   <button type="button" class="layui-btn layui-btn-danger remove-env" style="display: none;"><i class="layui-icon">&#xe640;</i></button>' +
                        '</div>'
                    );
                    envConfigs.append($emptyRow);
                }
                iframeWin.layui.form.render();
            },
            yes: function () {
            }
        });
    }

    $('#query').click(function(){
        search();
    });
    $(document).keyup(function(event){
        if(event.keyCode ==13){
            search();
        }
    });
    function search(){
        const content = $('#content');
        //执行重载
        table.reloadData('dockerDeploy', {
            method: 'get',
            page: {
                curr: 1 //重新从第 1 页开始
            }
            , where: {
                content: content.val(),
                projectId: $('#projectId').val(),
                dockerId: $('#dockerId').val(),
                namespaceId: $('#namespaceId').val(),
            }
        }, 'data');
    }
    $(function() {
        connect();  // 页面加载完成后自动连接 WebSocket
    })
    function connect() {
        //websocket对象
        let websocket = null;
        //判断当前浏览器是否支持WebSocket
        if ('WebSocket' in window) {
            websocket = new WebSocket("ws://"+sessionStorage.getItem('hostName')+"/websocket/logging");
        } else {
            console.error("不支持WebSocket");
        }

        //连接发生错误的回调方法
        websocket.onerror = function (e) {
            console.error("WebSocket连接发生错误",e);
        };
        //连接成功建立的回调方法
        websocket.onopen = function () {
            console.log("WebSocket连接成功")
        };
        //接收到消息的回调方法
        websocket.onmessage = function (event) {
            //追加
            if (event.data) {
                const data = JSON.parse(event.data);
                if (data.table = "deployDocker"){
                    if (data.type == 1){
                        search();
                    }else if (data.type == 2){
                        layer.msg(data.data,{icon:1,time:1000},function () {
                            search();
                        });
                    }else if (data.type == 3){
                        layer.msg(data.data,{icon:2,time:1000},function () {
                            search();
                        });
                    }
                }
            }
        };
        //连接关闭的回调方法
        websocket.onclose = function () {
            console.log("WebSocket连接关闭")
            // 后端重启，约定重新连接的时间间隔为5秒
            setTimeout(function() {
                connect();  // 重新连接 WebSocket
            }, 5000);
        };
    }



    let active = {
        selectTable: function () {
            search();
        },
    };
    function allLog() {
        layer.open({
            type: 2,
            title: '部署总览',
            area: ['1650px', '650px'],
            fix: false, //
            closeBtn: false,
            shift: 2,
            shadeClose: true,
            content: ["allLog.html"],
            success: function (layero, index) {

            },
            yes: function () {
            }
        });
    }


    //关闭页面
    function CloseWin() {
        window.location.reload(); // 父页面刷新
    }

    $(function () {
        getProject("")
        getDocker("")
        getNamespace("")
    })
    projectNameInput = function(e){
        const val = $("#projectName").val();
        getProject(val)
    }
    let projectData
    function getProject(projectName) {
        $.ajax({
            type: "GET",//方法类型
            dataType: "json",//预期服务器返回的数据类型
            url: "/admProject/getAll?name="+projectName,//url
            success: function (result) {
                projectData = result
                $("#projectId").html("");
                var html = "";
                $("#projectId").html("<option value=\"\">请选择项目</option>");
                if (result != null) {
                    $.each(result, function (index, item) {
                        html += "<option  value='" + item.id + "'>" + item.projectName + "</option>";
                    })
                }
                $("#projectId").append(html);
                form.render('select');
                if (projectName != null && projectName !=''){
                    $(".projectId").find(".layui-form-select").addClass("layui-form-selected")
                }
            },
            error: function () {
                alert("异常！");
            }
        });
    }
    // 监听下拉框改变事件,修改输入框中的内容
    form.on("select(projectId)",function(data){
        let value=data.value
        let selectObj=projectData.filter(item=>{
            return item.id==value
        })
        $("#projectName").val(selectObj[0].projectName);
    })


    namespaceNameInput = function(e){
        const val = $("#namespaceName").val();
        getNamespace(val)
    }
    let namespaceData
    function getNamespace(name) {
        $.ajax({
            type: "GET",//方法类型
            dataType: "json",//预期服务器返回的数据类型
            url: "/admNamespace/getAll?name="+name,//url
            success: function (result) {
                namespaceData = result
                $("#namespaceId").html("");
                var html = "";
                $("#namespaceId").html("<option value=\"\">请选择命名空间</option>");
                if (result != null) {
                    $.each(result, function (index, item) {
                        html += "<option  value='" + item.id + "'>" + item.name + "</option>";
                    })
                }
                $("#namespaceId").append(html);
                form.render('select');
                if (name != null && name !=''){
                    $(".namespaceId").find(".layui-form-select").addClass("layui-form-selected")
                }
            },
            error: function () {
                alert("异常！");
            }
        });
    }
    // 监听下拉框改变事件,修改输入框中的内容
    form.on("select(namespaceId)",function(data){
        let value=data.value
        let selectObj=namespaceData.filter(item=>{
            return item.id==value
        })
        $("#namespaceName").val(selectObj[0].name);
    })

    dockerNameInput = function(e){
        const val = $("#dockerName").val();
        getDocker(val)
    }
    let dockerData
    function getDocker(dockerName) {
        $.ajax({
            type: "GET",//方法类型
            dataType: "json",//预期服务器返回的数据类型
            url: "/admDocker/getAll?name="+dockerName,//url
            success: function (result) {
                dockerData = result
                $("#dockerId").html("");
                var html = "";
                $("#dockerId").html("<option value=\"\">请选择docker</option>");
                if (result != null) {
                    $.each(result, function (index, item) {
                        html += "<option  value='" + item.id + "'>" + item.dockerName + "</option>";
                    })
                }
                $("#dockerId").append(html);
                form.render('select');
                if (dockerName != null && dockerName !=''){
                    $(".dockerId").find(".layui-form-select").addClass("layui-form-selected")
                }
            },
            error: function () {
                alert("异常！");
            }
        });
    }
    // 监听下拉框改变事件,修改输入框中的内容
    form.on("select(dockerId)",function(data){
        let value=data.value
        let selectObj=dockerData.filter(item=>{
            return item.id==value
        })
        $("#dockerName").val(selectObj[0].dockerName);
    })



});
